package com.cms.controllers;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.cms.dto.UserReqDto;
import com.cms.dto.UserRespDto;
import com.cms.entity.User;
import com.cms.service.UserService;
import com.cms.support.Result;
import com.cms.support.SHA1Util;
import com.cms.support.StringEditor;

/**
 * @ClassName: UserController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author zhangp
 * @date 2016年3月31日 下午5:42:13
 * 
 */
@Controller
public class UserController {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(UserController.class);

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, false));
		binder.registerCustomEditor(String.class, new StringEditor());
	}

	@Autowired
	private UserService userService;

	@RequestMapping("/user")
	public String index(Model model) {
		return "user/index";
	}

	/**
	 * @Title: list
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param user
	 * @param iDisplayLength
	 * @param iDisplayStart
	 * @param sEcho
	 * @param model
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping("/user/list")
	public Object list(UserReqDto user, Integer iDisplayLength,
			Integer iDisplayStart, Integer sEcho, Model model) {
		try {
			UserRespDto userDto = userService.list(user, iDisplayStart,
					iDisplayLength);
			Long totalCount = userDto.getTotalCount();
			List<User> list = userDto.getUsers();
			JSONObject getObj = new JSONObject();
			getObj.put("sEcho", sEcho);// 不知道这个值有什么用,有知道的请告知一下
			getObj.put("iTotalRecords", totalCount);// 实际的行数
			getObj.put("iTotalDisplayRecords", totalCount);// 显示的行数,这个要和上面写的一样
			getObj.put("aaData", list);// 要以JSON格式返回
			return getObj;
		} catch (Exception e) {
			LOGGER.error(e.toString());
			return null;
		}
	}

	/**
	 * @Title: add
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @return String
	 * @throws
	 */
	@RequestMapping(value = "/user/add", method = RequestMethod.GET)
	public String add(Model model) {
		return "user/add";
	}

	/**
	 * @Title: doAdd
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param user
	 * @param model
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/user/add", method = RequestMethod.POST)
	public Object doAdd(User user, Model model) {
		try {
			if (userService.get(user.getUserName()) != null) {
				return new Result(false, "该用户名已注册");
			}
			user.setPassword(SHA1Util.hex_sha1("cms888"));
			user.setStatus(0);
			user.setCreateDate(new Date());
			userService.add(user);
		} catch (Exception e) {
			LOGGER.error("UserCardController 添加用户错误", e);
			return new Result(false, "系统异常,请稍后再试");
		}
		return new Result();
	}

	/**
	 * @Title: modify
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param userName
	 * @return String
	 * @throws
	 */
	@RequestMapping(value = "/user/modify", method = RequestMethod.GET)
	public String modify(Model model, String userName) {
		model.addAttribute("user", userService.get(userName));
		return "user/modify";
	}

	/**
	 * @Title: modify
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param user
	 * @param model
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/user/modify", method = RequestMethod.POST)
	public Object modify(User user, Model model) {
		try {
			if (user.getUserName() == null) {
				return new Result(false, "用户名不能为空");
			}
			user.setCreateDate(new Date());
			userService.update(user);
		} catch (Exception e) {
			LOGGER.error("UserCardController 修改用户信息错误,", e);
			return new Result(false, "系统异常,请稍后再试");
		}
		return new Result();
	}

	/**
	 * @Title: modifyPass
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param userName
	 * @param password
	 * @param newPass
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/user/updatePwd")
	public Object modifyPass(String userName, String password, String newPass) {
		User user;
		MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder(
				"md5");
		password = encoder.encodePassword(password, null);
		newPass = encoder.encodePassword(newPass, null);
		try {
			if (StringUtils.isBlank(userName)) {
				return new Result(false, "用户名不能为空");
			}
			if (StringUtils.isBlank(password)) {
				return new Result(false, "密码不能为空");
			}
			if (StringUtils.isBlank(newPass)) {
				return new Result(false, "新密码不能为空");
			}
			if (password.equals(newPass)) {
				return new Result(false, "新密码不能与旧密码相同");
			}
			user = userService.get(userName);
			user.setPassword(newPass);
			userService.update(user);
		} catch (Exception e) {
			LOGGER.error("用户修改密码异常", e);
			return new Result(false, "系统异常,请稍候再试");
		}
		return new Result();
	}

	/**
	 * @Title: view
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param userName
	 * @return String
	 * @throws
	 */
	@RequestMapping(value = "/user/view")
	public String view(Model model, String userName) {
		try {
			model.addAttribute("user", userService.get(userName));
		} catch (Exception e) {
			LOGGER.error("查看用户信息异常" + e.getLocalizedMessage());
			return "error";
		}
		return "user/view";
	}

	/**
	 * @Title: delete
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param userName
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/user/delete")
	public Object delete(Model model, @RequestParam String userName) {
		try {
			userService.delete(userName);
		} catch (Exception e) {
			LOGGER.error("删除用户异常", e);
			return new Result(false, "系统异常,请稍后再试");
		}
		return new Result();
	}

	/**
	 * @Title: toAudit
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param userName
	 * @return String
	 * @throws
	 */
	@RequestMapping(value = "/user/audit", method = RequestMethod.GET)
	public String toAudit(Model model, String userName) {
		model.addAttribute("user", userService.get(userName));
		return "user/audit";
	}

	/**
	 * @Title: audit
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param userName
	 * @param status
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/user/audit")
	public Object audit(Model model, String userName, Integer status) {
		try {
			User user = userService.get(userName);
			user.setStatus(status);
			userService.update(user);
		} catch (Exception e) {
			LOGGER.error("用户审核异常", e);
			return new Result(false, "系统异常,请稍后再试");
		}
		return new Result();
	}

	/**
	 * @Title: lock
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param userName
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/user/lock")
	public Object lock(Model model, @RequestParam String userName) {
		try {
			User user = userService.get(userName);
			user.setStatus(1);
			userService.update(user);
		} catch (Exception e) {
			LOGGER.error("冻结用户异常", e);
			return new Result(false, "系统异常,请稍后再试");
		}
		return new Result();
	}

	/**
	 * @Title: unlock
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param userName
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/user/unlock")
	public Object unlock(Model model, @RequestParam String userName) {
		try {
			User user = userService.get(userName);
			user.setStatus(0);
			userService.update(user);
		} catch (Exception e) {
			LOGGER.error("解冻用户异常", e);
			return new Result(false, "系统异常,请稍后再试");
		}
		return new Result();
	}

	/** 
	 * @Title: restPwd 
	 * @Description: TODO(这里用一句话描述这个方法的作用) 
	 * @param model
	 * @param userName
	 * @return Object 
	 * @throws 
	 */
	@ResponseBody
	@RequestMapping(value = "/user/resetPwd")
	public Object restPwd(Model model, @RequestParam String userName) {
		try {
			User user = userService.get(userName);
			MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder(
					"md5");
			String password = encoder.encodePassword("CMS#123", null);
			user.setPassword(password);
			userService.update(user);
		} catch (Exception e) {
			LOGGER.error("密码重置失败", e);
			return new Result(false, "系统异常,请稍后再试");
		}
		return new Result(true, "密码已重置为CMS#123，请登录修改密码！");
	}
}
